package com.example.demo.controller;

import com.example.demo.constant.ResultCode;
import com.example.demo.constant.Role;
import com.example.demo.dto.LoginDto;
import com.example.demo.dto.UserDto;
import com.example.demo.entity.CustomUsers;
import com.example.demo.entity.User;
import com.example.demo.entity.Users;
import com.example.demo.exception.PublicException;
import com.example.demo.exception.TokenException;
import com.example.demo.service.IUsersService;
import com.example.demo.service.Impl.SecurityUserDetail;
import com.example.demo.util.JwtUtilsSelf;
import com.example.demo.service.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    private static Logger logger = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private AuthenticationManager authenticationManager;
//    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtilsSelf jwtUtilsSelf;

    @Autowired
    private IUsersService usersService;

    @Autowired
    private RedisService redisService;

    @Value("${jwt.expiration}")
    private long expiration;
    @Autowired
    private IUsersService iUsersService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    // 登录接口
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginDto loginDto) {
        logger.warn("测试logger", loginDto);
        try {

            // 进行身份验证
            System.out.println(loginDto);
            logger.warn("测试logger111", loginDto);
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                            loginDto.getUsername(),
                            loginDto.getPassword()
                    )
            );
//            System.out.println(authentication.getPrincipal());
            logger.warn("测试logger222", loginDto);

//            try {
//                Authentication authentications = authenticationManager.authenticate(
//                        new UsernamePasswordAuthenticationToken(
//                                loginDto.getUsername(),
//                                loginDto.getPassword()
//                        )
//                );
//            } catch (InternalAuthenticationServiceException e) {
//                // 日志通常包含具体错误原因
//                // 异常堆栈可能指向数据库操作、加密服务等底层组件
//                logger.error("<authentication>", e);
////                e.printStackTrace();
//            }

            // 将认证信息设置到上下文中
            SecurityContextHolder.getContext().setAuthentication(authentication);

            // 获取认证后的用户详情
            CustomUsers authenticatedUser = (CustomUsers) authentication.getPrincipal();

            // 生成JWT令牌
            String token = jwtUtilsSelf.generateToken(authenticatedUser);

            // 将令牌存储到Redis
            redisService.saveToken(authenticatedUser.getUsername(), token, expiration);

            // 返回包含令牌的响应
            Map<String, Object> response = new HashMap<>();
            response.put("token", token);
            response.put("user", authenticatedUser);

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            System.out.println(e.getMessage());
            System.out.println(e);
            System.out.println("e.getMessage()");
            logger.error("auth错误", e);
            // 认证失败，返回错误信息
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(e.getMessage());
        }
    }

    @PostMapping("/register")
    public ResponseEntity<?> registerUser(@RequestBody Users users) {
        // 检查用户名是否已存在
//        if (userService.existsByUsername(users.getUsername())) {
//            return ResponseEntity.badRequest().body("Username already exists");
//        }
        if (iUsersService.hasUser(users.getUsername())) {
            throw new PublicException("用户已存在");
        }

        // 设置默认角色为普通用户
//        users.setRoles(Collections.singletonList(Role.USER));

        // 保存用户
//        userService.saveUser(user);
        users.setPassword(passwordEncoder.encode(users.getPassword()));
        iUsersService.save(users);
        return ResponseEntity.ok("User registered successfully");
    }

    // 注销接口
//    @PostMapping("/logout")
//    public ResponseEntity<?> logout() {
//        // 获取当前认证的用户
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//
//        if (authentication != null && authentication.getPrincipal() instanceof User) {
//            User user = (User) authentication.getPrincipal();
//            // 从Redis中删除令牌
//            redisService.deleteToken(user.getUsername());
//            // 清除SecurityContext
//            SecurityContextHolder.clearContext();
//        }
//
//        return ResponseEntity.ok("Logged out successfully");
//    }
}